﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Text;
using System.Xml;

using BP;
using BP.En;
using BP.DA;
using BP.Sys;
using BP.Web;
using BP.KM;
using BP.Port;

namespace CCOA.App
{
    /// <summary>
    /// KMDataService 的摘要说明:文档管理处理程序
    /// </summary>
    public class KMDataService : IHttpHandler
    {
        /// <summary>
        /// 封装有关个别 HTTP 请求的所有 HTTP 特定的信息
        /// </summary>
        HttpContext _Context = null;

        public string getUTF8ToString(string param)
        {
            return HttpUtility.UrlDecode(_Context.Request[param], System.Text.Encoding.UTF8);
        }

        public void ProcessRequest(HttpContext context)
        {
            _Context = context;

            if (BP.Web.WebUser.No == null)
                return;

            string method = string.Empty;
            //返回值
            string s_responsetext = string.Empty;
            if (!string.IsNullOrEmpty(_Context.Request["method"]))
                method = _Context.Request["method"].ToString();

            switch (method)
            {
                case "getkmsorts"://获取知识树
                    s_responsetext = GetKMSorts();
                    break;
                case "treesortmanage"://知识树操作
                    s_responsetext = TreeSortManage();
                    break;
                case "addfolder"://添加文件夹
                    s_responsetext = AddFolder();
                    break;
                case "updatesortname"://修改知识类别名称
                    s_responsetext = UpdateSortTreeName();
                    break;
                case "getmydoc"://获取我的文档
                    s_responsetext = GetMyDoc();
                    break;
                case "addmydoc"://添加文件
                    s_responsetext = AddMyDoc();
                    break;
                case "editmydoc"://修改文件
                    s_responsetext = EditMyDoc();
                    break;
                case "gettemplatedata"://分配权限，获取模版数据
                    s_responsetext = getTemplateData();
                    break;
                case "savesortrights"://保存权限
                    s_responsetext = SaveSortRights();
                    break;
                case "getnewlydoc"://获取最新文档
                    s_responsetext = GetNewLyDoc();
                    break;
                case "deldoc"://删除文件或文件夹
                    s_responsetext = DelDoc();
                    break;
                case "readtimeedit"://文件阅读次数
                    s_responsetext = ReadTimeEdit();
                    break;
                case "getshareinfo"://获取共享信息
                    s_responsetext = GetShareInfo();
                    break;
                case "sharefilemanage"://共享或取消共享文件
                    s_responsetext = ShareFileManage();
                    break;
                case "getempsharefiles"://同事共享文档
                    s_responsetext = GetEmpShareFiles();
                    break;
                case "getcompanydoc"://获取单位知识管理数据
                    s_responsetext = GetCompanyDoc();
                    break;
                case "getcompanydocforperson"://获取有权限查看的单位知识数据
                    s_responsetext = GetCompanyDocForPerson();
                    break;
            }
            if (string.IsNullOrEmpty(s_responsetext))
                s_responsetext = "";
            //组装ajax字符串格式,返回调用客户端
            _Context.Response.Charset = "UTF-8";
            _Context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            _Context.Response.ContentType = "text/html";
            _Context.Response.Expires = 0;
            _Context.Response.Write(s_responsetext);
            _Context.Response.End();
        }

        #region 最新文档操作
        /// <summary>
        /// 获取最新文档
        /// </summary>
        /// <returns></returns>
        private string GetNewLyDoc()
        {
            string content = getUTF8ToString("content");
            string sql = "SELECT * FROM V_KM_EmpDocTree where DocType=1 AND IsShare=1 AND FK_REmp='" + WebUser.No + "'";
            if (!string.IsNullOrEmpty(content))
            {
                sql += " AND (";
                sql += " Title like '%" + content + "%'";
                sql += " OR Doc like '%" + content + "%'";
                sql += " OR KeyWords like '%" + content + "%'";
                sql += " )";
            }
            sql += " order by RDT desc";
            DataTable dt = DBAccess.RunSQLReturnTable(sql);
            return BP.Tools.Json.ToJson(dt); // CCOA.Main.JsonConvert.GetJsonString(dt, false);
        }
        #endregion

        #region 我的文档操作
        /// <summary>
        /// 获取我的文档
        /// </summary>
        /// <returns></returns>
        private string GetMyDoc()
        {
            string sTreeNo = getUTF8ToString("TreeNo");
            string content = getUTF8ToString("content");
            //如果没有传入进行创建
            if (sTreeNo == "128")
            {
                Trees sort_Trees = new Trees();
                QueryObject sortInfo = new QueryObject(sort_Trees);
                sortInfo.AddWhere(TreeAttr.KMTreeCtrlWay, (int)KMTreeCtrlWay.ByEmp);
                sortInfo.addAnd();
                sortInfo.AddWhere(TreeAttr.No, sTreeNo);
                sortInfo.DoQuery();

                //判断个人文档类别是否存在
                if (sort_Trees == null || sort_Trees.Count == 0)
                {
                    Tree sort_Tree = new Tree();
                    sort_Tree.No = "128";
                    sort_Tree.Name = "个人文档";
                    sort_Tree.ParentNo = "99";
                    sort_Tree.KMTreeCtrlWay = KMTreeCtrlWay.ByEmp;
                    sort_Tree.Save();
                }
            }
            //文档目录
            string sql = "SELECT * FROM V_KM_DocTree WHERE KMTreeCtrlWay = 4 AND ParentNo='" + sTreeNo + "' AND FK_Emp='" + WebUser.No + "'";

            if (!string.IsNullOrEmpty(content))
            {
                sql += " AND (";
                sql += " Title like '%" + content + "%'";
                sql += " OR Doc like '%" + content + "%'";
                sql += " OR KeyWords like '%" + content + "%'";
                sql += " )";
            }
            FileInfo fileInfo = new FileInfo();
            DataTable dt = fileInfo.RunSQLReturnTable(sql);

            return BP.Tools.Json.ToJson(dt); 
        }

        /// <summary>
        /// 添加目录
        /// </summary>
        /// <returns></returns>
        private string AddFolder()
        {
            string sortTreeNo = getUTF8ToString("TreeNo");
            string folderName = getUTF8ToString("FolderName");
            //查找主目录
            Tree sort_Tree = new Tree(sortTreeNo);
            //新建子文件夹
            string cTreeNo = sort_Tree.DoCreateSubNode().No;
            Tree cTree = new Tree(cTreeNo);
            cTree.Name = folderName;
        //    cTree.IsDir = true;
            cTree.KMTreeCtrlWay = sort_Tree.KMTreeCtrlWay;
            cTree.IsShare = sort_Tree.IsShare;
            cTree.FileStatus = sort_Tree.FileStatus;
            cTree.Update();
            //如果为指定人共享
            if (sort_Tree.FileStatus == FileStatus.somePersons && sort_Tree.IsShare == "1")
            {
                //继承父项共享
                TreeEmps treeEmps = new TreeEmps();
                treeEmps.RetrieveByAttr(TreeEmpAttr.RefTreeNo, sortTreeNo);
                foreach (TreeEmp item in treeEmps)
                {
                    TreeEmp cTreeEmp = new TreeEmp();
                    cTreeEmp.RefTreeNo = cTreeNo;
                    cTreeEmp.FK_Emp = item.FK_Emp;
                    cTreeEmp.Insert();
                }
            }
            return "true";
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        private string AddMyDoc()
        {
            string fileName = getUTF8ToString("FileName");
            string keyWord = getUTF8ToString("KeyWord");
            string doc = getUTF8ToString("Doc");
            string sortTreeNo = getUTF8ToString("RefTreeNo");

            FileInfo addFile = new FileInfo();
            addFile.Title = fileName;
            addFile.KeyWords = keyWord;
            addFile.Doc = doc;
            addFile.RefTreeNo = sortTreeNo;
            addFile.Insert();
            return "true";
        }

        /// <summary>
        /// 修改文件
        /// </summary>
        /// <returns></returns>
        private string EditMyDoc()
        {
            string MyPK = getUTF8ToString("MyPK");
            string keyWord = getUTF8ToString("KeyWord");
            string doc = getUTF8ToString("Doc");
            FileInfo addFile = new FileInfo(MyPK);
            addFile.KeyWords = keyWord;
            addFile.Doc = doc;
            addFile.EDT = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
            addFile.EDTER = WebUser.No;
            addFile.Update();
            return "true";
        }

        /// <summary>
        /// 删除文件或文件夹
        /// </summary>
        /// <returns></returns>
        private string DelDoc()
        {
            try
            {
                string mypk = getUTF8ToString("MyPK");
                string isFolder = getUTF8ToString("IsFolder");
                //判断是文件夹
                if (isFolder == "true")
                {
                    //删除知识类别
                    Tree tree = new Tree(mypk);
                    tree.Delete();
                    //删除关联文件
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.Delete(FileInfoAttr.RefTreeNo, mypk);
                    //删除子项
                    DelChildFile(mypk);
                    return "true";
                }
                //删除文件
                FileInfo file = new FileInfo(mypk);
                file.Delete();
                return "true";
            }
            catch (Exception ex)
            {
            }
            return "false";
        }

        /// <summary>
        /// 删除子项
        /// </summary>
        /// <param name="TreeNo"></param>
        private void DelChildFile(string TreeNo)
        {
            //获取子项
            Trees trees = new Trees();
            trees.RetrieveByAttr(TreeAttr.ParentNo, TreeNo);
            foreach (Tree item in trees)
            {
                item.Delete();
                FileInfo fileInfo = new FileInfo();
                fileInfo.Delete(FileInfoAttr.RefTreeNo, item.No);
                //删除子项
                DelChildFile(item.No);
            }
        }

        #region 文件共享操作
        /// <summary>
        /// 获取共享信息
        /// </summary>
        /// <returns></returns>
        private string GetShareInfo()
        {
            StringBuilder append = new StringBuilder();
            string MyPK = getUTF8ToString("MyPK");
            string sql = "SELECT * FROM V_KM_DocTree WHERE MyPK='" + MyPK + "'";
            DataTable dt = DBAccess.RunSQLReturnTable(sql);

            //@0=私有@1=共享给全体人员@2=共享给指定人@3=删除
            string ShareType = dt.Rows[0]["FileStatus"].ToString();
            string IsShare = dt.Rows[0]["IsShare"].ToString();
            string SharePerson = GetSharePerson(MyPK);

            append.Append("{");
            append.Append(string.Format("ShareType:'{0}'", ShareType));
            append.Append(string.Format(",IsShare:'{0}'", IsShare));
            append.Append(string.Format(",SharePerson:{0}", SharePerson));
            append.Append("}");
            return append.ToString();
        }
        /// <summary>
        /// 获取共享给的人员
        /// </summary>
        /// <param name="MyPK"></param>
        /// <returns></returns>
        private string GetSharePerson(string MyPK)
        {
            string sharePersonVal = "";
            string sharePersonText = "";

            TreeEmps treeEmps = new TreeEmps();
            treeEmps.RetrieveByAttr(TreeEmpAttr.RefTreeNo, MyPK);
            foreach (TreeEmp item in treeEmps)
            {
                if (sharePersonVal.Length > 0) sharePersonVal += ",";

                sharePersonVal += item.FK_Emp;

                if (sharePersonText.Length > 0) sharePersonText += ",";

                sharePersonText += item.FK_EmpT;
            }
            return "{val:' " + sharePersonVal + "',text:'" + sharePersonText + "'}";
        }
        /// <summary>
        /// 共享文件
        /// </summary>
        /// <returns></returns>
        private string ShareFileManage()
        {
            string ShareType = getUTF8ToString("ShareType");
            string IsShare = getUTF8ToString("IsShare");
            string IsAllEmps = getUTF8ToString("IsAllEmps");
            string sharePersons = getUTF8ToString("SharePersons");
            string MyPK = getUTF8ToString("MyPK");

            bool bIsShare = IsShare == "checked" ? true : false;
            bool bIsAllEmps = IsAllEmps == "checked" ? true : false;

            //是否共享
            if (bIsShare)
            {
                //为文件夹
                if (ShareType == "0")
                {
                    ShareFolder(MyPK, bIsAllEmps, sharePersons);
                }
                else//文件
                {
                    ShareFiles(MyPK, bIsAllEmps, sharePersons);
                }
            }
            else
            {
                //为文件夹
                if (ShareType == "0")
                {
                    RemoveShareFolder(MyPK);
                }
                else//文件
                {
                    RemoveShareFiles(MyPK);
                }
            }
            return "true";
        }

        /// <summary>
        /// 共享文件夹
        /// </summary>
        /// <returns></returns>
        private string ShareFolder(string MyPK, bool isAllEmps, string sharePersons)
        {
            try
            {
                //共享文件夹
                Tree tree = new Tree(MyPK);
                tree.IsShare = "1";
                tree.FileStatus = isAllEmps ? FileStatus.anyPersons : FileStatus.somePersons;
                tree.Update();
                //如果不是全体人员,对人员进行授权
                TreeEmp treeEmp = new TreeEmp();
                treeEmp.Delete(TreeEmpAttr.RefTreeNo, MyPK);
                if (!isAllEmps)
                {
                    string[] arrary_Person = sharePersons.Split(',');
                    foreach (String str in arrary_Person)
                    {
                        treeEmp = new TreeEmp();
                        treeEmp.RefTreeNo = MyPK;
                        treeEmp.FK_Emp = str;
                        treeEmp.Insert();
                    }
                }
                //共享子文件
                Trees cTrees = new Trees();
                cTrees.RetrieveByAttr(TreeAttr.ParentNo, MyPK);
                foreach (Tree cItem in cTrees)
                {
                    ShareFolder(cItem.No, isAllEmps, sharePersons);
                }
                //文件夹下的文件
                FileInfos cFileInfos = new FileInfos();
                cFileInfos.RetrieveByAttr(FileInfoAttr.RefTreeNo, MyPK);
                foreach (FileInfo cFileItem in cFileInfos)
                {
                    ShareFiles(cFileItem.MyPK, isAllEmps, sharePersons);
                }
            }
            catch (Exception ex)
            {
                return "false";
            }
            return "true";
        }
        /// <summary>
        /// 取消共享文件夹
        /// </summary>
        /// <returns></returns>
        private string RemoveShareFolder(string MyPK)
        {
            try
            {
                //取消共享文件夹
                Tree tree = new Tree(MyPK);
                tree.IsShare = "0";
                tree.FileStatus = FileStatus.self;
                tree.Update();
                //取消对人员授权
                TreeEmp treeEmp = new TreeEmp();
                treeEmp.Delete(TreeEmpAttr.RefTreeNo, MyPK);

                //取消共享子文件
                Trees cTrees = new Trees();
                cTrees.RetrieveByAttr(TreeAttr.ParentNo, MyPK);
                foreach (Tree cItem in cTrees)
                {
                    RemoveShareFolder(cItem.No);
                }
                //文件夹下的文件
                FileInfos cFileInfos = new FileInfos();
                cFileInfos.RetrieveByAttr(FileInfoAttr.RefTreeNo, MyPK);
                foreach (FileInfo cFileItem in cFileInfos)
                {
                    RemoveShareFiles(cFileItem.MyPK);
                }
            }
            catch (Exception ex)
            {
                return "false";
            }
            return "true";
        }
        /// <summary>
        /// 共享文件
        /// </summary>
        private string ShareFiles(string MyPK, bool isAllEmps, string sharePersons)
        {
            try
            {
                //共享文件
                FileInfo fileInfo = new FileInfo(MyPK);
                fileInfo.IsShare = "1";
                fileInfo.FileStatus = isAllEmps ? FileStatus.anyPersons : FileStatus.somePersons;
                fileInfo.Update();
                //如果不是全体人员,对人员进行授权
                //删除对人员授权
                TreeEmp treeEmp = new TreeEmp();
                treeEmp.Delete(TreeEmpAttr.RefTreeNo, MyPK);
                if (!isAllEmps)
                {
                    string[] arrary_Person = sharePersons.Split(',');
                    foreach (String str in arrary_Person)
                    {
                        treeEmp = new TreeEmp();
                        treeEmp.RefTreeNo = MyPK;
                        treeEmp.FK_Emp = str;
                        treeEmp.Insert();
                    }
                }
            }
            catch (Exception ex)
            {
                return "false";
            }
            return "true";
        }

        /// <summary>
        /// 取消共享文件
        /// </summary>
        private string RemoveShareFiles(string MyPK)
        {
            try
            {
                //取消共享文件
                FileInfo fileInfo = new FileInfo(MyPK);
                fileInfo.IsShare = "0";
                fileInfo.FileStatus = FileStatus.self;
                fileInfo.Update();
                //删除对人员授权
                TreeEmp treeEmp = new TreeEmp();
                treeEmp.Delete(TreeEmpAttr.RefTreeNo, MyPK);
            }
            catch (Exception ex)
            {
                return "false";
            }
            return "true";
        }
        #endregion

        /// <summary>
        /// 文件阅读次数
        /// </summary>
        /// <returns></returns>
        private string ReadTimeEdit()
        {
            string MyPK = getUTF8ToString("MyPK");

            FileInfo fileInfo = new FileInfo();
            fileInfo.RetrieveByAttr(FileInfoAttr.MyPK, MyPK);
            if (fileInfo != null && fileInfo.MyPK != "")
            {
                fileInfo.ReadTimes = fileInfo.ReadTimes + 1;
                fileInfo.Update();
            }
            return "true";
        }
        #endregion

        #region 单位文档
        /// <summary>
        /// 获取知识文档
        /// </summary>
        /// <returns></returns>
        private string GetCompanyDoc()
        {
            string sTreeNo = getUTF8ToString("TreeNo");
            string content = getUTF8ToString("content");
            //如果没有传入进行创建
            if (sTreeNo == "99")
            {
                Trees sort_Trees = new Trees();
                QueryObject sortInfo = new QueryObject(sort_Trees);
                sortInfo.AddWhere(TreeAttr.No, sTreeNo);
                sortInfo.DoQuery();

                //判断知识管理是否存在
                if (sort_Trees == null || sort_Trees.Count == 0)
                {
                    Tree sort_Tree = new Tree();
                    sort_Tree.No = "99";
                    sort_Tree.Name = "知识树";
                    sort_Tree.ParentNo = "0";
                    sort_Tree.Save();
                }
            }
            //文档目录
            string sql = "SELECT * FROM V_KM_DocTree WHERE ParentNo='" + sTreeNo + "' and KMTreeCtrlWay<>4";
            
            if (!string.IsNullOrEmpty(content))
            {
                sql += " AND (";
                sql += " Title like '%" + content + "%'";
                sql += " OR Doc like '%" + content + "%'";
                sql += " OR KeyWords like '%" + content + "%'";
                sql += " )";
            }
            FileInfo fileInfo = new FileInfo();
            DataTable dt = fileInfo.RunSQLReturnTable(sql);

            return BP.Tools.Json.ToJson(dt); 
        }

        /// <summary>
        /// 获取知识文档
        /// </summary>
        /// <returns></returns>
        private string GetCompanyDocForPerson()
        {
            string sTreeNo = getUTF8ToString("TreeNo");
            string content = getUTF8ToString("content");
            //如果没有传入进行创建
            if (sTreeNo == "99")
            {
                Trees sort_Trees = new Trees();
                QueryObject sortInfo = new QueryObject(sort_Trees);
                sortInfo.AddWhere(TreeAttr.No, sTreeNo);
                sortInfo.DoQuery();

                //判断知识管理是否存在
                if (sort_Trees == null || sort_Trees.Count == 0)
                {
                    Tree sort_Tree = new Tree();
                    sort_Tree.No = "99";
                    sort_Tree.Name = "知识树";
                    sort_Tree.ParentNo = "0";
                    sort_Tree.Save();
                }
            }
            //文档目录
            string sql = "SELECT * FROM V_KM_EmpDocTree WHERE ParentNo='" + sTreeNo + "' and KMTreeCtrlWay<>4 and FK_REmp='" + WebUser.No + "'";

            if (!string.IsNullOrEmpty(content))
            {
                sql += " AND (";
                sql += " Title like '%" + content + "%'";
                sql += " OR Doc like '%" + content + "%'";
                sql += " OR KeyWords like '%" + content + "%'";
                sql += " )";
            }
            DataTable dt = DBAccess.RunSQLReturnTable(sql);

            return BP.Tools.Json.ToJson(dt); 
        }

        #endregion

        #region 同事共享文档
        /// <summary>
        /// 同事共享文档
        /// </summary>
        /// <returns></returns>
        private string GetEmpShareFiles()
        {
            string content = getUTF8ToString("content");
            string sql = "SELECT a.*,b.Name TreeName "
                        + " FROM V_KM_EmpDocTree a,KM_Tree b "
                        + " WHERE a.ParentNo=b.No AND a.IsShare =1 AND a.DocType=1 "
                        + " AND a.FK_REmp='" + WebUser.No + "'";
            if (!string.IsNullOrEmpty(content))
            {
                sql += " AND (";
                sql += " a.Title like '%" + content + "%'";
                sql += " OR a.Doc like '%" + content + "%'";
                sql += " OR a.KeyWords like '%" + content + "%'";
                sql += " )";
            }
            sql += " order by a.RDT desc";
            DataTable dt = DBAccess.RunSQLReturnTable(sql);

            return BP.Tools.Json.ToJson(dt); 
        }
        #endregion

        #region 知识树操作
        /// <summary>
        /// 获取知识树
        /// </summary>
        /// <returns></returns>
        private string GetKMSorts()
        {
            string checkedNodeIds = "", unCheckedNodeIds = "";
            string parentNo = getUTF8ToString("ParentNo");
            string isLoadChild = getUTF8ToString("isLoadChild");

            Trees sort_Trees = new Trees();
            QueryObject info = new QueryObject(sort_Trees);
            info.AddWhere(TreeAttr.ParentNo, parentNo);
            info.addAnd();
            info.AddWhere("KMTreeCtrlWay<>4");
            info.addOrderBy(TreeAttr.Idx);
            info.DoQuery();

            //第一次加载
            if (isLoadChild == "false")
            {
                StringBuilder appSend = new StringBuilder();
                appSend.Append("[");
                foreach (EntityTree item in sort_Trees)
                {
                    if (appSend.Length > 1) appSend.Append(",{"); else appSend.Append("{");

                    appSend.Append("\"id\":\"" + item.No + "\"");
                    appSend.Append(",\"text\":\"" + item.Name + "\"");

                    //节点图标
                    //if (!string.IsNullOrEmpty(item.ICON))
                    //{
                    //    string ico = "icon-" + item.ICON;
                    //    appSend.Append(",iconCls:\"");
                    //    appSend.Append(ico);
                    //    appSend.Append("\"");
                    //}
                    appSend.Append(",\"children\":");
                    appSend.Append(GetTreesByParentNo(item.No, checkedNodeIds, unCheckedNodeIds, false));
                    appSend.Append("}");
                }
                appSend.Append("]");
                return appSend.ToString();
            }
            //获取树节点数据
            return GetTreeList(sort_Trees, checkedNodeIds, unCheckedNodeIds);
        }
        /// <summary>
        /// 根据父节点编号获取子目录
        /// </summary>
        /// <returns></returns>
        private string GetTreesByParentNo(string parentNo, string checkedMenuIds, string unCheckedMenuIds, bool addChild)
        {
            StringBuilder menuAppend = new StringBuilder();
            //获取目录
            Trees sort_Trees = new Trees();

            QueryObject info = new QueryObject(sort_Trees);
            info.AddWhere(TreeAttr.ParentNo, parentNo);
            info.addAnd();
            info.AddWhere("KMTreeCtrlWay<>4");
            info.addOrderBy(TreeAttr.Idx);
            info.DoQuery();
            //是否添加下一级
            if (addChild)
            {
                menuAppend.Append("[");
                foreach (EntityTree item in sort_Trees)
                {
                    if (menuAppend.Length > 1) menuAppend.Append(",{"); else menuAppend.Append("{");

                    menuAppend.Append("\"id\":\"" + item.No + "\"");
                    menuAppend.Append(",\"text\":\"" + item.Name + "\"");

                    string ico = "";
                    //节点图标
                    //if (!string.IsNullOrEmpty(item.ICON))
                    //{
                    //    ico = "icon-" + item.ICON;
                    //}
                    //判断未完全选中
                    if (unCheckedMenuIds.Contains("," + item.No + ","))
                        ico = "collaboration";

                    menuAppend.Append(",iconCls:\"");
                    menuAppend.Append(ico);
                    menuAppend.Append("\"");
                    //判断选中
                    if (checkedMenuIds.Contains("," + item.No + ","))
                        menuAppend.Append(",\"checked\":true");

                    menuAppend.Append(",\"children\":");
                    menuAppend.Append(GetTreesByParentNo(item.No, checkedMenuIds, unCheckedMenuIds, false));
                    menuAppend.Append("}");
                }
                menuAppend.Append("]");

                return menuAppend.ToString();
            }
            return GetTreeList(sort_Trees, checkedMenuIds, unCheckedMenuIds);
        }

        /// <summary>
        /// 获取树节点列表
        /// </summary>
        /// <param name="ens"></param>
        /// <param name="checkIds"></param>
        /// <returns></returns>
        public string GetTreeList(Entities ens, string checkIds, string unCheckIds)
        {
            StringBuilder appSend = new StringBuilder();
            appSend.Append("[");
            foreach (EntityTree item in ens)
            {
                if (appSend.Length > 1) appSend.Append(",{"); else appSend.Append("{");

                appSend.Append("\"id\":\"" + item.No + "\"");
                appSend.Append(",\"text\":\"" + item.Name + "\"");

                //节点图标
                string ico = "";
                //if (!string.IsNullOrEmpty(item.ICON))
                //{
                //    ico = "icon-" + item.ICON;
                //}
                //判断未完全选中
                if (unCheckIds.Contains("," + item.No + ","))
                    ico = "collaboration";

                appSend.Append(",iconCls:\"");
                appSend.Append(ico);
                appSend.Append("\"");

                if (checkIds.Contains("," + item.No + ","))
                    appSend.Append(",\"checked\":true");

                //判断是否还有子节点
                Trees sort_Trees = new Trees();
                sort_Trees.RetrieveByAttr("ParentNo", item.No);
                if (sort_Trees != null && sort_Trees.Count > 0)
                {
                    appSend.Append(",state:\"closed\"");
                    appSend.Append(",\"children\":");
                    appSend.Append("[{");
                    appSend.Append(string.Format("\"id\":\"{0}\",\"text\":\"{1}\"", item.No + "01", "加载中..."));
                    appSend.Append("}]");
                }
                appSend.Append("}");
            }
            appSend.Append("]");

            return appSend.ToString();
        }

        /// <summary>
        /// 保存目录权限
        /// </summary>
        /// <returns></returns>
        private string SaveSortRights()
        {
            try
            {
                string TreeNo = getUTF8ToString("TreeNo");
                string saveNos = getUTF8ToString("ckNos");
                string curModel = getUTF8ToString("model");
                string saveChildNode = getUTF8ToString("saveChildNode");
                string[] str_Arrary = saveNos.Split(',');

                //按用户分配权限
                if (curModel == "emp")
                {
                    //删除目录下的所有用户
                    TreeEmps treeEmps = new TreeEmps();
                    treeEmps.Delete(TreeEmpAttr.RefTreeNo, TreeNo);

                    //对用户进行授权
                    foreach (string item in str_Arrary)
                    {
                        TreeEmp treeEmp = new TreeEmp();
                        treeEmp.FK_Emp = item;
                        treeEmp.RefTreeNo = TreeNo;
                        treeEmp.Insert();

                        //保存子目录
                        if (saveChildNode == "true")
                            SaveUserOfTreesChild(item, TreeNo, TreeNo, curModel);
                    }
                    return "true";
                }
                //按岗位分配权限
                if (curModel == "station")
                {
                    //删除目录下的所有岗位
                    TreeStations treeStations = new TreeStations();
                    treeStations.Delete(TreeStationAttr.RefTreeNo, TreeNo);

                    //对岗位进行授权
                    foreach (string item in str_Arrary)
                    {
                        TreeStation treeStation = new TreeStation();
                        treeStation.FK_Station = item;
                        treeStation.RefTreeNo = TreeNo;
                        treeStation.Insert();

                        //保存子
                        if (saveChildNode == "true")
                            SaveUserOfTreesChild(item, TreeNo, TreeNo, curModel);
                    }
                    return "true";
                }
                //删除目录下的部门
                TreeDepts treeDepts = new TreeDepts();
                treeDepts.Delete(TreeDeptAttr.RefTreeNo, TreeNo);

                //对部门进行授权
                foreach (string item in str_Arrary)
                {
                    TreeDept treeDept = new TreeDept();
                    treeDept.FK_Dept = item;
                    treeDept.RefTreeNo = TreeNo;
                    treeDept.Insert();
                    //对子节点进行授权
                    if (saveChildNode == "true")
                        SaveUserOfTreesChild(item, TreeNo, TreeNo, curModel);
                }
                return "true";
            }
            catch (Exception ex)
            {
                return "false";
            }
        }

        /// <summary>
        /// 保存知识类别子节点
        /// </summary>
        private void SaveUserOfTreesChild(string fk_No, string parentNo, string treeNos, string curModel)
        {
            //根据父节点编号获取子节点
            Trees trees = new Trees();
            trees.RetrieveByAttr(TreeAttr.ParentNo, parentNo);

            foreach (Tree cTree in trees)
            {
                if (treeNos.Contains(cTree.No))
                    continue;

                if (curModel == "emp")//按用户分配权限
                {
                    TreeEmp treeEmp = new TreeEmp();
                    treeEmp.FK_Emp = fk_No;
                    treeEmp.RefTreeNo = cTree.No;
                    treeEmp.Insert();
                }
                else if (curModel == "station")//按岗位分配权限
                {
                    TreeStation treeStation = new TreeStation();
                    treeStation.FK_Station = fk_No;
                    treeStation.RefTreeNo = cTree.No;
                    treeStation.Insert();
                }
                else if (curModel == "dept")//按部门分配权限
                {
                    TreeDept treeDept = new TreeDept();
                    treeDept.FK_Dept = fk_No;
                    treeDept.RefTreeNo = cTree.No;
                    treeDept.Insert();
                }
                SaveUserOfTreesChild(fk_No, cTree.No, treeNos, curModel);
            }
        }
        /// <summary>
        /// 获取模板数据
        /// </summary>
        /// <returns></returns>
        public string getTemplateData()
        {
            string sql = "";
            string TreeNo = getUTF8ToString("TreeNo");
            string model = getUTF8ToString("model");
            //按岗位分配
            if (model == "station")
            {
                sql = "SELECT No,Name,"
                    + "(SELECT COUNT(FK_Station) "
                    + " FROM KM_TreeStation "
                    + " WHERE FK_Station=Port_Station.No and RefTreeNo='" + TreeNo + "'"
                    + ") as isCheck "
                    + " FROM Port_Station"
                    + " order by No";
                //获取所有岗位
                Station station = new Station();
                DataTable dt_StationMenu = station.RunSQLReturnTable(sql);
                string rVal = BP.Tools.Json.ToJson(dt_StationMenu);
                rVal = "{station:" + rVal + "}";
                return rVal;
            }
            //按部门分配
            if (model == "dept")
            {
                sql = "SELECT No,Name,"
                    + "(SELECT COUNT(FK_Dept) "
                    + " FROM KM_TreeDept"
                    + " WHERE FK_Dept=Port_Dept.No AND RefTreeNo='" + TreeNo + "'"
                    + ") AS isCheck"
                    + " FROM Port_Dept"
                    + " ORDER by Idx";
                //获取所有部门
                Dept dept = new Dept();
                DataTable dt_GroupMenu = dept.RunSQLReturnTable(sql);

                string rVal = BP.Tools.Json.ToJson(dt_GroupMenu); 
                rVal = "{dept:" + rVal + "}";
                return rVal;
            }
            //按用户分配目录
            sql = "SELECT No,Name,FK_Dept,"
                    + "(SELECT COUNT(FK_Emp) "
                    + " FROM KM_TreeEmp"
                    + " WHERE FK_Emp=Port_Emp.No AND RefTreeNo='" + TreeNo + "'"
                    + ") AS isCheck"
                    + " FROM Port_Emp"
                    + " ORDER BY Name";
            string strdept = GetEmpDeptInfo();
            Emp emp = new Emp();
            DataTable dt_Emp = emp.RunSQLReturnTable(sql);
            string stremp = BP.Tools.Json.ToJson(dt_Emp);
            return "{bmList:" + strdept + ",empList:" + stremp + "}";
        }
        /// <summary>
        /// 获取包含人员的部门
        /// </summary>
        /// <returns></returns>
        public string GetEmpDeptInfo()
        {
            string sql = "SELECT distinct Port_Dept.No,Port_Dept.Name,Port_Dept.ParentNo,Port_Dept.Idx "
                + "FROM Port_Dept,port_emp  "
                + "WHERE Port_Emp.FK_Dept = Port_Dept.No order by Port_Dept.ParentNo,Port_Dept.Idx";
            Dept dept = new Dept();
            DataTable dt = dept.RunSQLReturnTable(sql);
            return BP.Tools.Json.ToJson(dt); 
        }

        /// <summary>
        /// 知识节点树操作
        /// </summary>
        /// <returns></returns>
        private string TreeSortManage()
        {
            string sortNo = getUTF8ToString("sortNo");
            string dowhat = getUTF8ToString("dowhat");
            string returnVal = "";
            Tree sort_Tree = new Tree();
            sort_Tree.RetrieveByAttr(TreeAttr.No, sortNo);

            switch (dowhat.ToLower())
            {
                case "sample"://新增同级节点   
                    returnVal = sort_Tree.DoCreateSameLevelNode().No;
                    break;
                case "children"://新增子节点
                    returnVal = sort_Tree.DoCreateSubNode().No;
                    break;
                case "doup"://上移
                    sort_Tree.DoUp();
                    break;
                case "dodown"://下移
                    sort_Tree.DoDown();
                    break;
                case "delete"://删除
                    sort_Tree.Delete();
                    break;
            }
            //返回
            return returnVal;
        }

        /// <summary>
        /// 修改知识类别名称
        /// </summary>
        /// <returns></returns>
        private string UpdateSortTreeName()
        {
            string sortNo = getUTF8ToString("sortNo");
            string sortName = getUTF8ToString("sortName");

            Tree sort_Tree = new Tree();
            sort_Tree.RetrieveByAttr(TreeAttr.No, sortNo);
            sort_Tree.Name = sortName;
            int i = sort_Tree.Update();
            if (i > 0)
            {
                return "true";
            }

            return "false";
        }
        #endregion

        #region 公共方法，转Json
        /// <summary>
        /// 将实体转为树形
        /// </summary>
        /// <param name="ens"></param>
        /// <param name="rootNo"></param>
        /// <param name="checkIds"></param>
        StringBuilder appendMenus = new StringBuilder();
        StringBuilder appendMenuSb = new StringBuilder();
        public void TansEntitiesToGenerTree(Entities ens, string rootNo, string checkIds)
        {
            EntityTree root = ens.GetEntityByKey(rootNo) as EntityTree;
            if (root == null)
                throw new Exception("@没有找到rootNo=" + rootNo + "的entity.");
            appendMenus.Append("[{");
            appendMenus.Append("\"id\":\"" + rootNo + "\"");
            appendMenus.Append(",\"text\":\"" + root.Name + "\"");

            //添加图标
            //if (!string.IsNullOrEmpty(root.ICON))
            //{
            //    appendMenus.Append(",iconCls:\"");
            //    appendMenus.Append("icon-" + root.ICON);
            //    appendMenus.Append("\"");
            //}
            // 增加它的子级.
            appendMenus.Append(",\"children\":");
            AddChildren(root, ens, checkIds);
            appendMenus.Append(appendMenuSb);
            appendMenus.Append("}]");
        }

        public void AddChildren(EntityTree parentEn, Entities ens, string checkIds)
        {
            appendMenus.Append(appendMenuSb);
            appendMenuSb.Clear();

            appendMenuSb.Append("[");
            foreach (EntityTree item in ens)
            {
                if (item.ParentNo != parentEn.No)
                    continue;

                if (checkIds.Contains("," + item.No + ","))
                    appendMenuSb.Append("{\"id\":\"" + item.No + "\",\"text\":\"" + item.Name + "\",\"checked\":true");
                else
                    appendMenuSb.Append("{\"id\":\"" + item.No + "\",\"text\":\"" + item.Name + "\",\"checked\":false");


                //添加图标
                //if (!string.IsNullOrEmpty(item.ICON))
                //{
                //    appendMenuSb.Append(",iconCls:\"");
                //    appendMenuSb.Append("icon-" + item.ICON);
                //    appendMenuSb.Append("\"");
                //}
                // 增加它的子级.
                appendMenuSb.Append(",\"children\":");
                AddChildren(item, ens, checkIds);
                appendMenuSb.Append("},");
            }
            if (appendMenuSb.Length > 1)
                appendMenuSb = appendMenuSb.Remove(appendMenuSb.Length - 1, 1);
            appendMenuSb.Append("]");
            appendMenus.Append(appendMenuSb);
            appendMenuSb.Clear();
        }

        /// <summary>
        /// 将实体类转为json格式
        /// </summary>
        /// <param name="ens"></param>
        /// <returns></returns>
        public string TranslateEntitiesToGridJsonOnlyData(BP.En.Entities ens)
        {
            Attrs attrs = ens.GetNewEntity.EnMap.Attrs;
            StringBuilder append = new StringBuilder();
            append.Append("[");

            foreach (Entity en in ens)
            {
                append.Append("{");
                foreach (Attr attr in attrs)
                {
                    append.Append(attr.Key + ":\"" + en.GetValStrByKey(attr.Key) + "\",");
                }
                append = append.Remove(append.Length - 1, 1);
                append.Append("},");
            }
            if (append.Length > 1)
                append = append.Remove(append.Length - 1, 1);
            append.Append("]");
            return append.ToString();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
    }
}